<template>
  <div class="workflow-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入工单名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <!-- <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button> -->
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增工作流
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="basicInfo.name" label="工单名称" min-width="150" />
        <el-table-column prop="basicInfo.description" label="描述" min-width="200" show-overflow-tooltip />
        <!-- <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleCopy(row)">
              复制
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 工作流配置弹窗 -->
    <WorkflowDialog
      v-model:visible="dialogVisible"
      :config="currentConfig"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search} from '@element-plus/icons-vue'
import WorkflowDialog from './dialog.vue'
import type { WorkflowConfiguration } from './types'
import { deleteWorkflow, getWorkflowPage } from '/@/api/workflow'
import { formatDate, formatPast } from '/@/utils/formatTime'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit' | 'copy'>('add')
const currentConfig = ref<WorkflowConfiguration | null>(null)

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const response = await getWorkflowPage({
      name: searchForm.name,
      page: pagination.current,
      size: pagination.size
    })

    tableData.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  getTableData()
}

// 新增
const handleAdd = () => {
  dialogMode.value = 'add'
  currentConfig.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogMode.value = 'edit'
  currentConfig.value = { ...row }
  dialogVisible.value = true
}

// 复制
const handleCopy = (row: any) => {
  dialogMode.value = 'copy'
  currentConfig.value = { ...row, id: undefined, name: `${row.name}_副本` }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工作流"${row.basicInfo.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteWorkflow(row.id)
    
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getTableData()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  getTableData()
}

// 格式化时间 - 使用utils中的formatDate和formatPast函数
const formatDateTime = (time: string | number | Date, useRelative: boolean = false) => {
  if (!time) return '-'
  
  // 可以选择使用相对时间格式（如"3天前"）或绝对时间格式
  if (useRelative) {
    return formatPast(time, 'YYYY-mm-dd HH:MM:SS')
  }
  
  return formatDate(new Date(time), 'YYYY-mm-dd HH:MM:SS')
}

// 初始化
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.workflow-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.search-container {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 6px;
}

:deep(.el-table__header) {
  background: #f5f7fa;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}
</style>